﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using XinYiOffice.Common;
using System.Data;
using System.Collections.Specialized;

namespace XinYiOffice.Web.InitControl
{
    public partial class SearchApp : System.Web.UI.UserControl
    {
        //拼接完成的 where 条件
        public string SqlWhere
        {
            get { return _sqlWhere; }
            set { _sqlWhere = value; }
        }
        private string _sqlWhere;

        public string UrlPas
        {
            get { return _urlpas; }
            set { _urlpas = value; }
        }
        private string _urlpas;

        public string strHTML = string.Empty;
        public StringBuilder sbHTML = new StringBuilder();

        private string strTemP = "<p>{0}</p>";
        private string strTemText = "<input type=\"text\" name=\"{0}\" id=\"{0}\" class=\"{1}\" style=\"{2}\" value=\"{3}\">";

        public static List<Model.SearchConfigItem> sciList { get { return _sciList; } set { _sciList = value; } }
        private static List<Model.SearchConfigItem> _sciList;

        public string TableName { get { return _TableName; } set { _TableName = value; } }
        private string _TableName;

        public Control con = new Control();
        public bool IsSearch = false;

        private Dictionary<string, string> dicUrlPas = new Dictionary<string, string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            string action = xytools.url_get("action");
            if (!string.IsNullOrEmpty(action))
            {
                switch (action)
                {
                    case "search":
                        IsSearch = true;
                        InitData(TableName);
                        break;
                }
            }
            else
            {
                if (!IsPostBack)
                {
                    InitData(TableName);
                }
            }
        }

        public void InitData(string TableName)
        {

            List<Model.SearchConfig> scList = new BLL.SearchConfig().GetModelList(string.Format("TableName='{0}'", TableName));
            Model.SearchConfig sc = new Model.SearchConfig();
            if (scList != null && scList.Count > 0)
            {
                sc = scList[0];
            }

            sciList = new BLL.SearchConfigItem().GetModelList(string.Format("SearchConfigId={0}", sc.Id));
            if (sciList == null) { return; }
            int i = 1;

            foreach (Model.SearchConfigItem sci in sciList)
            {
                string eleNameId = string.Format("_search_name_{0}", i);
                string eleId = string.Format("_search_ele_{0}", i);
                string value = IsSearch ? xytools.url_get(eleId) : string.Empty;

                StringBuilder sbP = new StringBuilder("<p>");
                sbP.Append(CreateLiteral(sci, eleNameId));
                sbP.AppendFormat(" {0} ", sci.PrefixChar);
                SetSearchItem(ref sbP, sci, eleId, value);//设置表单
                sbP.AppendFormat(" {0} ", sci.SuffixChar);
                sbP.Append("</p>");

                sbHTML.Append(sbP);

                dicUrlPas.Add(eleId, eleId);
                i++;
            }

            sbHTML.AppendFormat("<input  id=\"{0}\" name=\"{0}\" value=\"{1}\"  type=\"hidden\" />", "hid_ele_count", i);//追加个隐藏域,保存字段个数
            sbHTML.Append("<input  id=\"action\" name=\"action\" value=\"search\"  type=\"hidden\" />");
            sbHTML.AppendFormat("<input  id=\"hidSearchConfigId\" name=\"hidSearchConfigId\" value=\"{0}\"  type=\"hidden\" />", sc.Id);

            dicUrlPas.Add("hid_ele_count", "hid_ele_count");
            dicUrlPas.Add("action", "action");
            dicUrlPas.Add("hidSearchConfigId", "hidSearchConfigId");
            dicUrlPas.Add("page","page");

            System.Collections.Specialized.NameValueCollection coll = new System.Collections.Specialized.NameValueCollection(Request.QueryString);

            if (coll != null && coll.Count > 0)
            {
                foreach (string _col in coll.AllKeys)
                {
                    if (!string.IsNullOrEmpty(_col) && dicUrlPas.ContainsKey(_col))
                    {
                        continue;
                    }

                    string[] value = coll.GetValues(_col);

                    sbHTML.AppendFormat("<input  id=\"{0}\" name=\"{0}\" value=\"{1}\"  type=\"hidden\" />", _col, SafeConvert.ToString(value[0]));
                }
            }

            if (IsSearch)
            {
                sbHTML.Append("<script>$(\".show_search_box\").show();</script>");
            }

            strHTML = sbHTML.ToString();
        }

        /// <summary>
        /// 设置一个隐藏域的键值对
        /// </summary>
        public void SetHideKey(string key, string value)
        {
            strHTML += string.Format("<input  id=\"{0}\" name=\"{0}\" value=\"{1}\"  type=\"hidden\" />", key, value);
        }

        public void SetSqlWhere()
        {
            StringBuilder _sb = new StringBuilder();

            int i = 1;
            string _t = "{0}";
            int SearchConfigId = SafeConvert.ToInt(xytools.url_get("hidSearchConfigId"));

            sciList = new BLL.SearchConfigItem().GetModelList(string.Format("SearchConfigId={0}", SearchConfigId));
            if (sciList == null) { return; }

            foreach (Model.SearchConfigItem sci in sciList)
            {
                string _value = string.Empty;
                bool iscontinue = false;//若为 下拉框的时候 值又为0 则表明是选择的 全部,此字段不参与,若为文本，值又为空，则不参与

                _value = xytools.url_get(string.Format("_search_ele_{0}", i));
                string[] str = _value.Split(',');
                if (str != null && str.Length > 0)
                {
                    _value = SafeConvert.ToString(str[0]);
                }

                iscontinue = ((_value == string.Empty) ? true : false);
                _sb.Append(sci.PrefixRelChar == "null" ? " " : sci.PrefixRelChar).Append(" ");//前置关系

                if (!iscontinue)
                {
                    _sb.Append(sci.FieldName).Append(" ");

                    #region 值之间关系
                    if (sci.ValueType == 1) { _t = "'{0}'"; } else { _t = "{0}"; }
                    switch (sci.ValueRelChar.ToLower())
                    {
                        case "=":
                            _sb.AppendFormat("=" + _t, _value).Append(" ");
                            break;

                        case ">":
                            _sb.AppendFormat(">" + _t, _value).Append(" ");
                            break;

                        case "<":
                            _sb.AppendFormat("<" + _t, _value).Append(" ");
                            break;

                        case "<=":
                            _sb.AppendFormat("<=" + _t, _value).Append(" ");
                            break;

                        case ">=":
                            _sb.AppendFormat(">=" + _t, _value).Append(" ");
                            break;

                        case "like":
                            _sb.AppendFormat(" like '%{0}%'", _value).Append(" ");
                            break;

                        case "not in":
                            _sb.AppendFormat(" not in (" + _t + ")", _value).Append(" ");
                            break;

                        case "in":
                            _sb.AppendFormat(" in (" + _t + ")", _value).Append(" ");
                            break;
                    }
                    #endregion
                }
                else
                {
                    _sb.Append(" 1=1 ");
                }

                _sb.Append(sci.SuffixRelChar == "null" ? " " : sci.SuffixRelChar);//后置关系


                i++;
            }

            SqlWhere = _sb.ToString();
        }

 



        /// <summary>
        /// 设置表单项
        /// </summary>
        /// <param name="con"></param>
        /// <param name="sci"></param>
        /// <param name="eleId"></param>
        /// <returns></returns>
        protected void SetSearchItem(ref StringBuilder con, Model.SearchConfigItem sci, string eleId, string value)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                Model.SearchDataSoure sds = new BLL.SearchDataSoure().GetModel(SafeConvert.ToInt(sci.SearchDataSoureId));
                if (sds == null|| sds.FormType==null)
                {
                    con.Append(CreateText(eleId, value));
                }

                switch (SafeConvert.ToInt(sds.FormType))
                {
                    //文本
                    case 1:
                        //con.Controls.Add(CreateText(sds, eleId));
                        con.Append(CreateText(sds, eleId, value));
                        break;

                    //下拉列表
                    case 2:
                        //con.Controls.Add(CreateDropDownList(sds, eleId));
                        con.Append(CreateDropDownList(sds, eleId, value));
                        break;

                    //复选框
                    case 3:
                        break;

                    //单选
                    case 4:
                        break;

                    //时间选择
                    case 5:
                        break;

                    default:
                        con.Append(CreateText(eleId, value));
                        break;
                }
            }
            catch (Exception ex)
            {
                //EasyLog.WriteLog(ex);
            }
            finally
            {
            }



            //return string.Empty;
        }


        /// <summary>
        /// 创建表单元素 名称
        /// </summary>
        /// <param name="sci"></param>
        /// <param name="eleId"></param>
        /// <returns></returns>
        protected string CreateLiteral(Model.SearchConfigItem sci, string eleId)
        {
            return string.Format("<span id=\"{0}\" style=\"border:none;\">{1}</span>", eleId, sci.DisplayName);
        }


        /// <summary>
        /// 创建文本框
        /// </summary>
        /// <param name="sds"></param>
        /// <param name="eleId"></param>
        /// <returns></returns>
        protected string CreateText(Model.SearchDataSoure sds, string eleId, string value)
        {
            return string.Format(this.strTemText, eleId, sds.FormClass, sds.FormStyle, value);
        }


        protected string CreateText(string eleId, string value)
        {
            return string.Format(this.strTemText, eleId, string.Empty, string.Empty, value);
        }


        protected string CreateDropDownList(Model.SearchDataSoure sds, string eleId, string value)
        {
            StringBuilder sbSelect = new StringBuilder();
            sbSelect.AppendFormat("<select id=\"{0}\" name=\"{0}\" class=\"{1}\" style=\"{2}\">", eleId, sds.FormClass, sds.FormStyle);
            string strOption = "<option value=\"{0}\" {1} >{2}</option>";


            switch (sds.DataSoureType)
            {
                //数据库
                case 1:
                    DataSet ds = DbHelperSQL.Query(sds.DataSoureConntion);
                    if (sds.DataType == 4)
                    {
                        if (ds != null)
                        {
                            sbSelect.AppendFormat(strOption, "", string.Empty, "全部");
                            DataTable dt = ds.Tables[0];
                            foreach (DataRow dr in dt.Rows)
                            {
                                string _displayname = SafeConvert.ToString(dr[sds.DisplayValue]);
                                string _tvalue = SafeConvert.ToString(dr[sds.TrueValue]);
                                string _isselected = (_tvalue == value) ? "selected=\"selected\"" : string.Empty;

                                sbSelect.AppendFormat(strOption, _tvalue, _isselected, _displayname);
                            }


                        }

                    }
                    break;

                //文本文件
                case 2:
                    break;

                //网址
                case 3:
                    break;

                //Execl文件
                case 4:
                    break;

                //xml文件
                case 5:
                    break;

            }
            sbSelect.Append("</select>");
            return sbSelect.ToString();

        }
    }
}